﻿using System;
using System.IO;
using System.Windows.Forms;
using mki.Backup.Objects.Properties;

namespace mki.Backup.Objects.Dialogs
{
	/// <summary>
	/// Represents the FolderFileBrowserEditorForm class
	/// </summary>
	public partial class FolderFileBrowserEditorForm : Form
	{
		#region Constructors (1)

		/// <summary>
		/// Initializes a new instance of the <see cref="FolderFileBrowserEditorForm"/> class.
		/// </summary>
		public FolderFileBrowserEditorForm()
		{
			InitializeComponent();

			// init
			this.StartPosition = FormStartPosition.CenterParent;
			this.DialogResult = DialogResult.None;
			this.browseButton.Click += new EventHandler(browseButtonClick);
			this.saveButton.Click += new EventHandler(saveButtonClick);
			this.fileNameTextBox.Enter += (s, e) => this.fileNameToolTip.SetToolTip(this.fileNameTextBox, Resources.FileNameToolTip);
		}

		#endregion Constructors

		#region Properties (1)

		// Public Properties (1) 

		/// <summary>
		/// Gets the name of the path and file.
		/// </summary>
		/// <value>The name of the path and file.</value>
		public String PathAndFileName
		{
			get { return Path.Combine(this.directoryTextBox.Text, this.fileNameTextBox.Text); }
			set { this.extractPathAndFileName(value); }
		}

		#endregion Properties

		#region Methods (3)

		// Private Methods (3) 

		/// <summary>
		/// Browses the button click.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void browseButtonClick(object sender, EventArgs e)
		{
			var folderDialg = new FolderBrowserDialog { ShowNewFolderButton = true, SelectedPath = this.directoryTextBox.Text };
			if (folderDialg.ShowDialog() == DialogResult.OK)
			{
				this.directoryTextBox.Text = folderDialg.SelectedPath;
			}
		}

		/// <summary>
		/// Extracts the name of the path and file.
		/// </summary>
		/// <param name="pathAndFileName">Name of the path and file.</param>
		private void extractPathAndFileName(String pathAndFileName)
		{
			if (!String.IsNullOrWhiteSpace(pathAndFileName))
			{
				this.directoryTextBox.Text = Path.GetDirectoryName(pathAndFileName);
				this.fileNameTextBox.Text = Path.GetFileName(pathAndFileName);
			}
		}

		/// <summary>
		/// Saves the button click.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void saveButtonClick(object sender, EventArgs e)
		{
			if (!Directory.Exists(this.directoryTextBox.Text))
			{
				MessageBox.Show(String.Format(Resources.ErrorFolderDoesNotExist, this.directoryTextBox.Text), Resources.ErrorHeadline, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			this.DialogResult = DialogResult.OK;
		}

		#endregion Methods
	}
}
